package com.jweb.framework.http.support;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.util.Assert;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.util.CookieGenerator;
import org.springframework.web.util.WebUtils;
/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：主题解析
 */
public class SmartThemeResolver extends CookieGenerator implements ThemeResolver{
	
	public static final String ORIGINAL_DEFAULT_THEME = "default" ;
	public static final String THEME_ATTRIBUTE_NAME = SmartThemeResolver.class.getName() + ".THEME";
	public static final String DEFAULT_COOKIE_NAME = SmartThemeResolver.class.getName() + ".THEME";
	private String defaultTheme = "default";
	private boolean useCookie ;
	
	public SmartThemeResolver(){
		
		setCookieName(DEFAULT_COOKIE_NAME);
		setCookieMaxAge(Integer.valueOf(2592000));
	}
	
	public void setDefaultTheme(String defaultTheme) {
		this.defaultTheme = defaultTheme;
	}

	public void setUseCookie(boolean useCookie) {
		this.useCookie = useCookie;
	}

	public String resolveThemeName(HttpServletRequest request) {
		
		String str = (String) request.getAttribute(THEME_ATTRIBUTE_NAME);
		if(str!=null){
			return str ;
		}
		
		str = (String) WebUtils.getSessionAttribute(request, THEME_ATTRIBUTE_NAME);
		if(str==null && this.useCookie){
			Cookie cookie = WebUtils.getCookie(request, getCookieName());
			if(cookie!=null){
				return cookie.getValue();
			}
		}
		
		if(str==null){
			str = this.defaultTheme ;
		}
		
		if(str!=null){
			request.setAttribute(THEME_ATTRIBUTE_NAME, str);
		}
		
		return str ;
	}

	public void setThemeName(HttpServletRequest request,HttpServletResponse response, String themeName) {
		
		if(themeName!=null){
			setSession(request , THEME_ATTRIBUTE_NAME , themeName);
			if(this.useCookie){
				addCookie(response, themeName);
			}
		}
		else{
			setSession(request, THEME_ATTRIBUTE_NAME, null);
			if(this.useCookie){
				removeCookie(response);
			}
		}
		
	}

	private void setSession(HttpServletRequest request,String themeAttributeName, String themeName) {
		
		Assert.notNull(request, "request must not be null ");
		HttpSession httpSession = request.getSession(false);
		if(httpSession!=null){
			if(themeName!=null){
				httpSession.setAttribute(themeAttributeName, themeName);
			}
			else{
				httpSession.removeAttribute(themeAttributeName);
			}
		}
		
	}
	

}
